//
//  BGMApplePayViewController.m
//  BGM
//
//  Created by 我要变好看 on 2019/1/17.
//  Copyright © 2019 com.alirtc.demo. All rights reserved.
//

#import "BGMApplePayViewController.h"
#import "Common.h"
#import "BGMHTTP.h"
#import <AlipaySDK/AlipaySDK.h>
#import "BGMUser.h"
#import "SVProgressHUD.h"

#import <StoreKit/StoreKit.h>
@interface BGMApplePayViewController ()
<
SKPaymentTransactionObserver,SKProductsRequestDelegate
>

@property (nonatomic, strong)UITextField *payText;
@property (nonatomic, strong)NSString *orderID;

@property (nonatomic, assign)float money;

//@property (nonatomic, strong)NSString *apple_productId;  //1 支付宝 2 内购
@end

@implementation BGMApplePayViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.navview.hidden = NO;
    self.titleBtn.hidden = NO;
    CGRect rect = self.titleBtn.frame;
    rect.size.width = rect.size.width+70;
    self.titleBtn.frame = rect;
    
    if (self.type == BGMPushildRed) {
        [self.titleBtn setTitle:@"帮转红包" forState:UIControlStateNormal];
//        self.apple_productId = @"ForwardRedEnvelope";
    }else if(self.type == BGMThanksRed){
        [self.titleBtn setTitle:@"答谢红包" forState:UIControlStateNormal];
//        self.apple_productId = @"ThanksRedEnvelope";
    }else if (self.type ==BGMAddRed ){
        [self.titleBtn setTitle:@"补加红包" forState:UIControlStateNormal];
//        self.apple_productId = @"Addredenvelope";
        self.backBtn.hidden = NO;
    }
    
    [[SKPaymentQueue defaultQueue] addTransactionObserver:self];
    
    UIView *bgView = [[UIView alloc]initWithFrame:CGRectMake(15, self.navview.frame.size.height+15, SCREENW-30, 300)];
    bgView.backgroundColor = [UIColor whiteColor];
    bgView.layer.cornerRadius = 8;
    bgView.layer.masksToBounds = YES;
    [self.view addSubview:bgView];
    
    
    UILabel *label1 = [[UILabel alloc]initWithFrame:CGRectMake(15, 0, 80, 60)];
    label1.text = @"付款方式";
    label1.textColor = bgmmainColor;
    [bgView addSubview:label1];
    
   
    
    UIImageView *payView1 = [[UIImageView alloc]initWithFrame:CGRectMake(120, 20, 20, 20)];
    [payView1 setImage:[UIImage imageNamed:@"applePay"]];
    [bgView addSubview:payView1];
    
    UILabel *label21 = [[UILabel alloc]initWithFrame:CGRectMake(160, 15, 70, 30)];
    label21.text = @"苹果支付";
    label21.font = [UIFont systemFontOfSize:13];
    label21.textColor = bgmsmallColor;
    label21.tag = 100;
    [bgView addSubview:label21];
    
    
    
    UILabel *line1 = [[UILabel alloc]initWithFrame:CGRectMake(0, 60, SCREENW, 0.3)];
    line1.backgroundColor = [UIColor grayColor];
    line1.alpha = 0.1;
    [bgView addSubview:line1];
    
    UILabel *label3 = [[UILabel alloc]initWithFrame:CGRectMake(15, 70, 100, 30)];
    label3.text = @"红包总金额";
    label3.textColor = bgmmainColor;
    [bgView addSubview:label3];
    
   
    
    
    UIButton *btn1 = [[UIButton alloc]initWithFrame:CGRectMake(15, 130, 100, 40)];
    [btn1 setTitle:@"￥6" forState:UIControlStateNormal];
    [btn1 setTitleColor:[UIColor whiteColor] forState:UIControlStateSelected];
    [btn1 setTitleColor:bgmsmallColor forState:UIControlStateNormal];
    btn1.titleLabel.font = [UIFont boldSystemFontOfSize:16];
    btn1.backgroundColor = bgmyelloeColor;
    btn1.layer.cornerRadius = 8;
    btn1.layer.masksToBounds = YES;
    [bgView addSubview:btn1];
    btn1.selected = YES;
    btn1.tag = 888;
    
    
    UIButton *btn2 = [[UIButton alloc]initWithFrame:CGRectMake(135, 130, 100, 40)];
    [btn2 setTitle:@"￥12" forState:UIControlStateNormal];
    [btn2 setTitleColor:[UIColor whiteColor] forState:UIControlStateSelected];
    [btn2 setTitleColor:bgmsmallColor forState:UIControlStateNormal];
    btn2.backgroundColor = bgmColor(244, 244, 244);
    btn2.layer.cornerRadius = 8;
    btn2.layer.masksToBounds = YES;
    [bgView addSubview:btn2];
    btn2.tag = 889;

    [btn1 addTarget:self action:@selector(clickMenoy:) forControlEvents:UIControlEventTouchUpInside];
    [btn2 addTarget:self action:@selector(clickMenoy:) forControlEvents:UIControlEventTouchUpInside];

    
    
    UIButton *btn = [[UIButton alloc]initWithFrame:CGRectMake(15, bgView.frame.size.height-70, bgView.frame.size.width-30, 50)];
    btn.backgroundColor = bgmyelloeColor;
    btn.layer.cornerRadius = 5;
    btn.layer.masksToBounds = YES;
    [btn setTitle:@"确定" forState:UIControlStateNormal];
    [btn setTitleColor:bgmmainColor forState:UIControlStateNormal];
    [bgView addSubview:btn];
    [btn addTarget:self action:@selector(clickBtn) forControlEvents:UIControlEventTouchUpInside];
    
    
    
}

- (void)clickMenoy:(UIButton *)btn{
    UIButton *btn1 = [self.view viewWithTag:888];
    UIButton *btn2 = [self.view viewWithTag:889];

    if (btn1 == btn) {
        btn1.selected = YES;
        btn1.backgroundColor = bgmyelloeColor;
        btn2.selected = NO;
        btn2.backgroundColor = bgmColor(244, 244, 244);
        self.money = 6.0;

    }else{
        btn1.selected = NO;
        btn1.backgroundColor = bgmColor(244, 244, 244);

        btn2.selected = YES;
        btn2.backgroundColor = bgmyelloeColor;
        
        self.money = 12.0;

    }
    
}

- (void)clickBtn{
    [SVProgressHUD show];
    
    if ([SKPaymentQueue canMakePayments]) {
        [self BGMapplePay];
    }else{
        [SVProgressHUD showInfoWithStatus:@"appid拒绝苹果内购，那就选择支付宝支付吧~"];
        [SVProgressHUD dismiss];
    }
    
    
}



#pragma mark 苹果内购
- (void)BGMapplePay{
    //bundleid+xxx 就是你添加内购条目设置的产品ID
    NSArray *product = [[NSArray alloc] initWithObjects:@"ForwardRedEnvelope",@"ForwardRedEnvelope_12",nil];
    NSSet *nsset = [NSSet setWithArray:product];
    //初始化请求
    SKProductsRequest *request = [[SKProductsRequest alloc] initWithProductIdentifiers:nsset];
    request.delegate = self;
    //开始请求
    [request start];
}


#pragma mark - SKProductsRequestDelegate
//接收到产品的返回信息，然后用返回的商品信息进行发起购买请求
- (void)productsRequest:(SKProductsRequest *)request didReceiveResponse:(SKProductsResponse *)response NS_AVAILABLE_IOS(3_0)
{
    NSArray *product = response.products;
    
    //如果服务器没有产品
    if([product count] == 0){
        NSLog(@"没有该商品");
        return;
    }
    
    SKProduct *requestProduct = nil;
    for (SKProduct *pro in product) {
        
//        NSLog(@"%@", [pro description]);
//        NSLog(@"%@", [pro localizedTitle]);
//        NSLog(@"%@", [pro localizedDescription]);
//        NSLog(@"%@", [pro price]);
//        NSLog(@"%@", [pro productIdentifier]);
        float price = [[pro price] floatValue];
        if(self.money == price){
            requestProduct = pro;
        }
        
        
    }
    
//    //发送购买请求
    SKMutablePayment *payment = [SKMutablePayment paymentWithProduct:requestProduct];
    //可以是userId，也可以是订单id，跟你自己需要而定
    payment.applicationUsername = [NSString stringWithFormat:@"userId=%@,productid=%@",[BGMUser shareInstance].userId,[requestProduct productIdentifier]];
    [[SKPaymentQueue defaultQueue] addPayment:payment];
    
    
    
}

#pragma mark - SKRequestDelegate
//请求失败
- (void)request:(SKRequest *)request didFailWithError:(NSError *)error
{
    NSLog(@"error:%@", error);
}

//请求结束
- (void)requestDidFinish:(SKRequest *)request
{
    NSLog(@"请求结束");
}

#pragma mark - SKPaymentTransactionObserver
//监听购买结果
- (void)paymentQueue:(SKPaymentQueue *)queue updatedTransactions:(NSArray *)transactions
{
    for(SKPaymentTransaction *tran in transactions){
        switch (tran.transactionState) {
            case SKPaymentTransactionStatePurchased:
            {
                NSLog(@"交易完成");
                [self completeTransaction:tran];
                [[SKPaymentQueue defaultQueue] finishTransaction:tran];
            }
                break;
            case SKPaymentTransactionStatePurchasing:
                NSLog(@"商品添加进列表");
                
                break;
            case SKPaymentTransactionStateFailed:
            {
                NSLog(@"交易失败");
                [SVProgressHUD showInfoWithStatus:@"appid账号/密码不正确，请重新输入"];
                [[SKPaymentQueue defaultQueue] finishTransaction:tran];
            }
                break;
            default:
                break;
        }
    }
}

//交易结束,当交易结束后还要去appstore上验证支付信息是否都正确,只有所有都正确后,我们就可以给用户方法我们的虚拟物品了。
- (void)completeTransaction:(SKPaymentTransaction *)transaction
{
    
    // 验证凭据，获取到苹果返回的交易凭据
    // appStoreReceiptURL iOS7.0增加的，购买交易完成后，会将凭据存放在该地址
    NSURL *receiptURL = [[NSBundle mainBundle] appStoreReceiptURL];
    // 从沙盒中获取到购买凭据
    NSData *receiptData = [NSData dataWithContentsOfURL:receiptURL];
    //发送POST请求，对购买凭据进行验证
    //测试验证地址：https://sandbox.itunes.apple.com/verifyReceipt
    //正式验证地址：https://buy.itunes.apple.com/verifyReceipt
    NSString *AppStore_URL = @"https://sandbox.itunes.apple.com/verifyReceipt";
    NSURL *url = [NSURL URLWithString:AppStore_URL];
    NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:15.0f];
    urlRequest.HTTPMethod = @"POST";
    NSString *encodeStr = [receiptData base64EncodedStringWithOptions:NSDataBase64EncodingEndLineWithLineFeed];
    //    _receipt = encodeStr;
    NSString *payload = [NSString stringWithFormat:@"{\"receipt-data\" : \"%@\"}", encodeStr];
    NSData *payloadData = [payload dataUsingEncoding:NSUTF8StringEncoding];
    urlRequest.HTTPBody = payloadData;
    
    NSData *result = [NSURLConnection sendSynchronousRequest:urlRequest returningResponse:nil error:nil];
    //    [NSURLSession dataTaskWithRequest:completionHandler:]
    
    
    if (result == nil) {
        NSLog(@"验证失败");
        return;
    }
    
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:result options:NSJSONReadingAllowFragments error:nil];
    NSLog(@"请求成功后的数据:%@",dic);
    //这里可以通过判断 state == 0 验证凭据成功，然后进入自己服务器二次验证，,也可以直接进行服务器逻辑的判断。
    //本地服务器验证成功之后别忘了 [[SKPaymentQueue defaultQueue] finishTransaction: transaction];
    
//    NSString *productId = transaction.payment.productIdentifier;
//    NSString *applicationUsername = transaction.payment.applicationUsername;
    
    //    NSLog(@"applicationUsername++++%@",applicationUsername);
    //    NSLog(@"payment.productIdentifier++++%@",productId);
    
    if (dic != nil) {
        [self postNotificationCenterPaySuccess];
    }
    
}
- (void)postNotificationCenterPaySuccess{
    [SVProgressHUD dismiss];
    if (self.thankUserID.length>0) {  //答谢好友
        [SVProgressHUD showSuccessWithStatus:@"答谢完成"];
        [[NSNotificationCenter defaultCenter]postNotificationName:@"pay_money_thanks" object:nil];
        
    }else{
        
    }
    
    if(self.type ==BGMAddRed){  //补加
        [[NSNotificationCenter defaultCenter]postNotificationName:@"add_pay_money" object:nil];
        [self clickBack];
    }else if (self.type == BGMThanksRed){ //答谢
        [self.navigationController popViewControllerAnimated:YES];
        
    }else if (self.type == BGMPushildRed){ //帮转
        
        [[NSNotificationCenter defaultCenter]postNotificationName:@"pay_money" object:[NSString stringWithFormat:@"%.2f",self.money]];
        [self.navigationController popViewControllerAnimated:YES];
        
    }
    [self performSelector:@selector(postMoeny) withObject:nil afterDelay:3];
    
}
- (void)postMoeny{
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        //类型（1 红包支付(只传 usersId)   2 帮转红包补加支付(传 usersId, publishId)   3 完成帮忙答谢支付（传usersId, acknowledgeUsers））
        NSDictionary *param;
        if (self.type == BGMPushildRed) {//帮转红包
            param = @{@"userToken":[BGMUser shareInstance].userToken,
                      @"usersId":[BGMUser shareInstance].userId,
                      @"type":@"1",
                      @"money":[NSString stringWithFormat:@"%.2f",self.money]
                      };
        }else if(self.type == BGMThanksRed){//答谢红包
            param = @{@"userToken":[BGMUser shareInstance].userToken,
                      @"usersId":[BGMUser shareInstance].userId,
                      @"acknowledgeUsers":self.thankUserID,
                      @"money":[NSString stringWithFormat:@"%.2f",self.money],
                      @"type":@"3",
                      };
        }else if (self.type ==BGMAddRed ){//补加红包
            param = @{@"userToken":[BGMUser shareInstance].userToken,
                      @"usersId":[BGMUser shareInstance].userId,
                      @"publishId":self.publishId,
                      @"money":[NSString stringWithFormat:@"%.2f",self.money],
                      @"type":@"2",
                      };
        }
        
        [BGMHTTP requestWithMethodName:@"alipay/paySuccrss" parameters:param completion:^(BOOL success, NSError *error, NSDictionary *result) {
            NSLog(@"向后台发送支付金额d成功");
        }];
    });
    
}



- (void)clickBack{
    
    if (self.type == BGMPushildRed) {
        [self.navigationController popViewControllerAnimated:YES];
        
    }else if(self.type == BGMThanksRed){
        [self.titleBtn setTitle:@"答谢红包" forState:UIControlStateNormal];
        [self.navigationController popViewControllerAnimated:YES];
        
    }else if (self.type ==BGMAddRed ){
        [self dismissViewControllerAnimated:YES completion:nil];
    }
    
}

- (void)dealloc{
    //移除观察者 self
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [[SKPaymentQueue defaultQueue] removeTransactionObserver:self];
}





@end
